package com.cloudkinto.session;

import com.cloudkinto.entity.UserDo;
import com.cloudkinto.service.user.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Transactional(rollbackFor = Exception.class)//事务回滚
@Service
public class UserSessionManagerImpl implements UserSessionManager {

    private static Logger logger = LoggerFactory.getLogger(UserSessionManagerImpl.class);

    @Resource
    private UserService userService;

    @Resource
    private UserSessionRepository userSessionRepository;

    @Override
    public UserSession getSession(String sessionId) {
        return userSessionRepository.querySession(sessionId);
    }

    @Override
    public UserSession getSession(HttpServletRequest request) throws UserSessionException {
        String sessionId = request.getHeader(UserSession.SESSION_ID_KEY);
        UserSession userSession = userSessionRepository.querySession(sessionId);
        if (userSession == null) {
            // 会话失效
            request.getSession().removeAttribute(UserSession.SESSION_ID_KEY);
            throw new UserSessionException("用户会话不存在，或已过期，请重新登陆");
        }
        return userSession;
    }

    public UserSession keepAlive(HttpServletRequest request) throws UserSessionException {
        Object obj = request.getSession().getAttribute(UserSession.SESSION_ID_KEY);
        if (obj != null) {
            UserSession session = UserSession.class.cast(obj);
            userSessionRepository.saveSession(session);
            return session;
        }
        return null;
    }

    @Override
    public UserSession createSession(UserDo userDo) throws UserSessionException {
        UserSession session = new UserSession();
        try {
            session.setSessionId(UUID.randomUUID().toString());
            session.setUserId(userDo.getId());
            session.setCompanyId(userDo.getCompanyId());
            session.setShopId(userDo.getShopId());
            session.setStorageId(userDo.getStorageId());
            userSessionRepository.saveSession(session);

            return session;
        } catch (Exception ex) {
            throw new UserSessionException("指定用户不存在，无法创建会话");
        }
    }


    @Override
    public void clearSession(String sessionId) {
        userSessionRepository.removeSession(sessionId);
    }
}
